package com.tjf.traffic.utils;


import android.Manifest;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

import com.tjf.traffic.bean.TrafficInfo;

import java.util.ArrayList;
import java.util.List;


/**
 * @author: tjf
 * @date: 2022-12-10
 * @desc： 获取手机安装的应用程序的工具类
 */
public class TrafficManagerApp {

    private PackageManager pm;

    public TrafficManagerApp(Context context) {
        super();
        pm = context.getPackageManager();
    }

    /**
     * 获取拥有internet权限的应用列表
     *
     * @return
     */
    public List<TrafficInfo> getInternetTrafficInfos() {
        List<TrafficInfo> trafficInfos = new ArrayList<TrafficInfo>();
        //获取手机中安装的并且具有权限的应用  PackageManager.GET_UNINSTALLED_PACKAGES |
        List<PackageInfo> installedPackages = pm.getInstalledPackages(
                PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_PERMISSIONS);
        for (PackageInfo info : installedPackages) {
            //获取权限数组
            String[] permissions = info.requestedPermissions;
            if (permissions != null && permissions.length > 0) {
                for (String permission : permissions) {
                    if (permission.equals(Manifest.permission.INTERNET)) {
                        ApplicationInfo applicationInfo = info.applicationInfo;
                        Drawable icon = applicationInfo.loadIcon(pm);
                        String appname = applicationInfo.loadLabel(pm).toString();
                        String packagename = applicationInfo.packageName;
                        int uid = applicationInfo.uid;
                        TrafficInfo trafficInfo = new TrafficInfo(icon, appname, packagename, uid);
                        trafficInfos.add(trafficInfo);
                    }
                }
            }
        }
        return trafficInfos;
    }

    /**
     * 获取所有 的应用列表
     *
     * @return
     */
    public List<TrafficInfo> getInstalledApplications() {
        List<TrafficInfo> trafficInfos = new ArrayList<TrafficInfo>();

        List<ApplicationInfo> installedPackages = pm.getInstalledApplications(
                0);
        for (ApplicationInfo applicationInfo : installedPackages) {

            Drawable icon = applicationInfo.loadIcon(pm);
            String appname = applicationInfo.loadLabel(pm).toString();
            String packagename = applicationInfo.packageName;
            int uid = applicationInfo.uid;
            TrafficInfo trafficInfo = new TrafficInfo(icon, appname, packagename, uid);
            trafficInfos.add(trafficInfo);
        }
        return trafficInfos;
    }

}
